package top.ljjapp.soufang.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import top.ljjapp.soufang.entity.User;
import top.ljjapp.soufang.service.IUserService;

/**
 * 自定义认证实现
 */
public class AuthProvider implements AuthenticationProvider {
    @Autowired
    private IUserService userService;

    //MD5编码
    private final Md5PasswordEncoder passwordEncoder = new Md5PasswordEncoder();

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取输入的用户名，密码
        String userName = authentication.getName();
        String  inputPassword = (String) authentication.getCredentials();
        //根据用户名查到用户
        User user = userService.findUserByNmae(userName);
        //判断用户为空
        if (user == null){
            throw  new AuthenticationCredentialsNotFoundException("authErro");
        }
        //验证
        if (this.passwordEncoder.isPasswordValid(user.getPassword(),inputPassword,user.getId())){
            return new UsernamePasswordAuthenticationToken(user , null ,user.getAuthorities());
        }

        throw  new BadCredentialsException("authError");
    }


    @Override
    public boolean supports(Class<?> authtication) {
        return true;
    }
}
